package com.navy.chen.tetrisgame.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.navy.chen.tetrisgame.bean.Tetris;
import com.navy.chen.tetrisgame.tool.Config;
import com.navy.chen.tetrisgame.tool.DrawHelper;
import com.navy.chen.tetrisgame.interfaces.ProductListener;
import com.navy.chen.tetrisgame.R;
import com.navy.chen.tetrisgame.tool.Tools;

import java.util.Arrays;

/**
 * Created by Administrator on 2017/12/5.
 */
public class TetrisPreview extends View implements ProductListener {
    private final String TAG = Config.TAG + getClass().getSimpleName();
    private final static int length  =4;
    private int side = 20;//px

    private Tetris tetris;
    private float side_length= 0 ;
    public TetrisPreview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int density = (int) getResources().getDisplayMetrics().density;
        Log.d(TAG, String.format("density = %d", density));
        int w = length * side*density;
        setMeasuredDimension(w, w);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d(TAG, "ononDraw");
        side_length = getWidth()*1.0f/length;
        DrawHelper.getInstance().drawBg(canvas, Tools.getColor(getContext(), R.color.tetris_content_bg),
                length, length, side_length);
        if (tetris == null){
            initTetris();

        }
        Log.d(TAG, String.format("tetris x = %f, y = %f",tetris.getX(), tetris.getY()));
        Log.d(TAG, Arrays.deepToString(tetris.getMatrix()));
        DrawHelper.getInstance().drawATetris(tetris, canvas, side_length);
    }

    public Tetris getTetris() {
        return tetris;
    }

    public void setTetris(Tetris tetris) {
        this.tetris = tetris;
    }

    @Override
    public Tetris productTetris() {

        Tetris copy = (Tetris) tetris.clone();
        initTetris();
        postInvalidate();
        return copy;
    }

    private void initTetris(){
        tetris = Tetris.randomTetris();
        if (tetris.getMatrix().length == 4){
            tetris.setX(0);
            tetris.setY(0);
        } else {
            int blankLeft = Tools.getBlankLeft(tetris.getMatrix());
            tetris.setX(side_length- blankLeft*side_length);
            int blankTop = Tools.getBlankTop(tetris.getMatrix());
            tetris.setY(side_length-blankTop*side_length);
        }
    }
}
